import { Component, Input, Output, EventEmitter, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
    selector: 'dm-tool-tabs',
    templateUrl: 'tabs.html'
})

export class DmTabs implements AfterViewInit {

    @ViewChild('tabsGroup') tabsGroup: ElementRef;
    @ViewChild('tabsScroll') tabsScroll: any;

    @Input() tabsData: Array<string>;
    @Output() onActived = new EventEmitter<number>();

    tabs: Array<any>;
    cursor: any;
    lastActiveTab: any;
    windowWidth: number;
    tabsIsScrolling: boolean = false;

    constructor() { }

    ngAfterViewInit() {
        this.tabs = this.tabsGroup.nativeElement.children;
        this.cursor = this.tabsGroup.nativeElement.lastElementChild;
        this.cursor.style.width = this.tabs[0].offsetWidth + 'px';
        this.lastActiveTab = this.tabs[0];
        this.windowWidth = window.screen.width;
    }

    tabTapped(e, i) {
        if (!this.tabsIsScrolling && this.lastActiveTab != this.tabs[i]) {
            this.activeItem(i);
            this.onActived.emit(i);
        }
    }

    activeItem(index: number) {
        this.lastActiveTab.classList.remove('active');
        this.tabs[index].classList.add('active');
        this.cursor.style.left = this.tabs[index].offsetLeft + 'px';
        this.cursor.style.width = this.tabs[index].offsetWidth + 'px';
        this.lastActiveTab = this.tabs[index];
        if ((this.tabs[index].offsetLeft - this.tabsScroll.scrollElement.scrollLeft) < 60) {
            setTimeout(() => {
                this.scrollTo(this.tabs[index].offsetLeft - 60, 150);
            }, 200);
        } else if ((this.tabs[index].offsetLeft + this.tabs[index].offsetWidth - this.tabsScroll.scrollElement.scrollLeft) > (this.windowWidth - 60)) {
            setTimeout(() => {
                this.scrollTo(this.tabs[index].offsetLeft - 60, 250);
            }, 200);
        }
    }

    scrollTo(position: number, duration: number) {
        let scrollStep = (position - this.tabsScroll.scrollElement.scrollLeft) / (duration / 15);
        this.tabsIsScrolling = true;
        let scrollInterval = setInterval(() => {
            this.tabsScroll.scrollElement.scrollLeft = this.tabsScroll.scrollElement.scrollLeft + scrollStep;
        }, 15);
        setTimeout(() => {
            clearInterval(scrollInterval);
            this.tabsIsScrolling = false;
        }, duration + 50);
    }

}
